<template>
  <div class="login-container">
    <div class="login-form">
      <h2 class="login-title">系统登录</h2>
      <el-form :model="loginForm" :rules="rules" ref="loginFormRef" @submit.prevent="handleLogin">
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" name="username" placeholder="用户名" prefix-icon="User"
            autocomplete="username" />
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="loginForm.password" name="password" type="password" placeholder="密码" prefix-icon="Lock"
            autocomplete="password" show-password @keyup.enter="handleLogin" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleLogin" :loading="loading" style="width: 100%">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '../stores/user'
import AuthApi from '../api/system/auth'
import { useLocaleStore } from '@/stores/locale'
import { useThemeStore } from '@/stores/theme'
import encryptor from '@/utils/rsa'

const router = useRouter()
const userStore = useUserStore()
const localeStore = useLocaleStore()
const themeStore = useThemeStore()
const loginFormRef = ref()
const loading = ref(false)

const loginForm = ref({
  username: '',
  password: ''
})

const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

const handleLogin = async () => {
  try {
    loading.value = true
    const valid = await loginFormRef.value.validate()
    if (!valid) return

    // 模拟登录API调用
    const resp = await AuthApi.login({ 'name': loginForm.value.username, 'password': encryptor.encryptor.encrypt(loginForm.value.password) })

    // 设置token
    userStore.setToken(resp.access_token)
    userStore.setEncryptUser(resp.user)

    localeStore.setLocaleLanguage('zh')
    themeStore.setTheme('light')

    ElMessage.success('登录成功')
    router.push('/home')
  } catch (error) {
    ElMessage.error('登录失败，请检查用户名和密码')
    console.error('Login error:', error)
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.login-form {
  width: 400px;
  padding: 30px;
  border-radius: 6px;
}

.login-title {
  text-align: center;
  margin-bottom: 30px;
}
</style>
